import {Component, ElementRef, Inject, OnInit, Renderer2, ViewChild, ViewEncapsulation} from '@angular/core';
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {SCRIPT_LOADER, ScriptLoader} from "@core/script-loader/script-loader";
import {TrainService} from "@train/train.service";
import {ActivatedRoute} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";

@Component({
  selector: 'seed-tactical-detail',
  templateUrl: './tactical-detail.component.html',
  styleUrls: ['./tactical-detail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class TrainTacticalDetailComponent implements OnInit {

  @ViewChild('tactical') tactical: ElementRef;
  @ViewChild('play') play: ElementRef;
  @ViewChild('suspended') suspended: ElementRef;
  public playbook;
  public firstPlay = true;
  public btnStatus = {
    first: false,
    last: true,
    next: true,
    pause: false,
    play: true,
    previous: false
  };
  public tacticalInfoIndex: number = 0;
  public tacticalInfo: any = {};
  public tacticalInfoContent: any = {};


  constructor(
    private render2: Renderer2,
    private _imgService: ImageServeService,
    private trainService: TrainService,
    private route: ActivatedRoute,
    private authService: AuthService,
    @Inject(SCRIPT_LOADER) public scriptLoader: ScriptLoader
  ) {
  }

  /**
   * @author guoqs1331
   * @time 2018/3/12
   * @description 调用BasketBallPlaybook
   */
  playBook(str: string): void {
    const screenWidth = document.body.clientWidth,
      scalePercent = (screenWidth * 2 / 750) * 0.5;
    this.playbook.deserialize(str);
    this.render2.setStyle(this.tactical.nativeElement.querySelector('div'), 'zoom', scalePercent);
    if (this.tacticalInfoContent.type && this.tacticalInfoContent.type !== 'full') {
      this.render2.setStyle(this.tactical.nativeElement.querySelector('div'), 'height', '475px');
    }
    this.playbook.update();
  }

  /**
   * @author guoqs1331
   * @time 2018/3/13
   * @description
   */
  getIcon(name: string): string {
    return this._imgService.getIcon(name);
  }

  /**
   * @author guoqs1331
   * @time 2018/3/12
   * @description 播放
   */
  start(): void {
    this.resetFirstPlay();
    this.playbook.play();
  }

  /**
   * @author guoqs1331
   * @time 2018/3/21
   * @description 重播
   */
  rePlay(): void {
    this.resetFirstPlay();
    this.playbook.first();
    this.playbook.play();
  }

  /**
   * @author guoqs1331
   * @time 2018/3/13
   * @description 暂停
   */
  pause(): void {
    this.playbook.pause();
  }

  /**
   * @author guoqs1331
   * @time 2018/3/13
   * @description rest firstPlay值为true
   */
  resetFirstPlay(): void {
    !this.firstPlay && (this.firstPlay = true);
  }

  /**
   * @author guoqs1331
   * @time 2018/3/13
   * @description 上一帧
   */
  previous(): void {
    this.resetFirstPlay();
    this.playbook.previous();
  }

  /**
   * @author guoqs1331
   * @time 2018/3/13
   * @description 下一帧
   */
  next(): void {
    this.resetFirstPlay();
    this.playbook.next();
  }

  /**
   * @author guoqs1331
   * @time 2018/3/13
   * @description 初始化
   */
  initTactical(content): void {
    const self = this;
    self.playbook = new BasketBallPlaybook(self.tactical.nativeElement);

    self.playbook.onstatechange = function (event) {
      let dom = this.play.nativeElement;
      while (dom) {
        let id = dom.id;
        if (id && id in event) {
          dom.disabled = !event[id];
        }
        dom = dom.nextSibling;
      }
      self.btnStatus = event;
      // console.log("第" + (self.playbook.index + 1) + "帧");
      self.tacticalInfoIndex = self.playbook.index;
      self.setCurTacticalInfo();
      //最后一帧播完重置
      if (!self.btnStatus.play && !self.btnStatus.pause && !self.btnStatus.next) {
        self.firstPlay = false;
      }
    };
    this.playBook(content);
  }

  /**
   * @author guoqs1331
   * @time 2018/3/20
   * @description 当前帧信息
   */
  setCurTacticalInfo() {
    // console.log('this.tacticalInfoIndex', this.tacticalInfoIndex);
    this.tacticalInfo = this.tacticalInfoContent['frames'][this.tacticalInfoIndex];
    // console.log(this.tacticalInfoContent['frames']);
    // this.tacticalInfo['describe'] && (this.tacticalInfo['describe'] = decodeURIComponent(this.tacticalInfo['describe']));
  }

  async ngOnInit() {
    const param = {
      tacticId: this.route.snapshot.params['tacticId'],
      orgUserId: this.authService.getAuthOrgId()
    };
    const playBookPro = this.scriptLoader.load('basketball_playbook'),
      tacticInfoPro = this.trainService.getTacticInfo(param).toPromise();
    const resArray = await Promise.all([tacticInfoPro, playBookPro]);
    if (resArray['0'] && resArray['0']['data'] && resArray['0']['data']['content']) {
      this.tacticalInfoContent = JSON.parse(resArray['0']['data']['content']);
      this.setCurTacticalInfo();
      this.initTactical(this.tacticalInfoContent);
    }
  }

}
